//
//  CourseGrammarViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/28.
//

#import "CourseGrammarViewController.h"
#import <PDFKit/PDFKit.h>

@interface CourseGrammarViewController ()

@property (nonatomic, strong)PDFView *pdfView;

@end

@implementation CourseGrammarViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
}

-(void)createUI{
    
     [self.customNavigationBar setTitle:@"本课语法"];
    
    // 初始化 PDFView 并设置初始框架
    self.pdfView = [[PDFView alloc] initWithFrame:CGRectMake(16, kYM_NAVIGATIONBAR_HEIGHT + 12, self.currentAvailableWidth - 32, self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 12)];
    self.pdfView.backgroundColor = [UIColor clearColor];
    self.pdfView.hidden = YES;
    // 加载 PDF 文件
    if (self.file) {
        NSURL *pdfURL = [NSURL URLWithString:self.file];
        PDFDocument *pdfDocument = [[PDFDocument alloc] initWithURL:pdfURL];
        self.pdfView.document = pdfDocument;
    }
    // 设置 PDFView 的内容缩放
    [self.view addSubview:self.pdfView];

    // 调整 PDFView 的高度
    [self adjustPDFViewHeight];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.pdfView.hidden = NO;
        [self scrollToTop];
    });
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            self.pdfView.frame = CGRectMake(16, kYM_NAVIGATIONBAR_HEIGHT + 12, self.currentAvailableWidth - 32, self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 12);
            [self adjustPDFViewHeight];
            [self scrollToTop];
        });
    }
}


- (void)adjustPDFViewHeight {
    if (self.pdfView.document) {
        // 获取PDF文档的页数
        NSUInteger pageCount = self.pdfView.document.pageCount;
        CGFloat totalHeight = 0.0;

        // 遍历每一页，计算总高度
        for (NSUInteger i = 0; i < pageCount; i++) {
            PDFPage *page = [self.pdfView.document pageAtIndex:i];
            CGRect pageRect = [page boundsForBox:kPDFDisplayBoxMediaBox];

            // 计算当前页的缩放比例和高度
            CGFloat scale = self.pdfView.bounds.size.width / pageRect.size.width;
            CGFloat pageHeight = pageRect.size.height * scale;

            // 累加所有页面的高度
            totalHeight += pageHeight;
        }

        // 限制总高度不超过屏幕可用高度
        CGFloat maxHeight = self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - 12;
        CGFloat finalHeight = MIN(totalHeight, maxHeight);

        // 设置PDFView的高度
        CGRect pdfViewFrame = self.pdfView.frame;
        pdfViewFrame.size.height = finalHeight;
        self.pdfView.frame = pdfViewFrame;

        // 设置显示模式
        self.pdfView.autoScales = YES;
        self.pdfView.displayMode = kPDFDisplaySinglePageContinuous;
        self.pdfView.displayDirection = kPDFDisplayDirectionVertical;

        // 确保第一页显示在顶部
        [self.pdfView goToPage:[self.pdfView.document pageAtIndex:0]];
    }
}

// 强制滚动到顶部
- (void)scrollToTop {
    UIScrollView *scrollView = [self findScrollViewInView:self.pdfView];
    if (scrollView) {
        [scrollView setContentOffset:CGPointZero animated:NO];
    }
}

// 在 PDFView 中找到 UIScrollView
- (UIScrollView *)findScrollViewInView:(UIView *)view {
    if ([view isKindOfClass:[UIScrollView class]]) {
        return (UIScrollView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIScrollView *scrollView = [self findScrollViewInView:subview];
        if (scrollView) {
            return scrollView;
        }
    }
    return nil;
}

@end
